package com.jlc.o2o.service.impl;

import com.jlc.o2o.dao.ShopDao;
import com.jlc.o2o.dto.ShopExecuption;
import com.jlc.o2o.entity.Shop;
import com.jlc.o2o.enums.ShopSateEnum;
import com.jlc.o2o.exceptions.ShopOperationException;
import com.jlc.o2o.service.ShopService;
import com.jlc.o2o.util.ImageUtil;
import com.jlc.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.Date;

@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopDao shopDao;

    @Transactional
    @Override
    public ShopExecuption addShop(Shop shop, CommonsMultipartFile shopImg) {
        if (shop == null) {
            return new ShopExecuption(ShopSateEnum.OFFLINE);

        }
        try {
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            int i = shopDao.insertShop(shop);
            if(i <= 0){
                throw  new ShopOperationException("店铺创建失败");
            }else{
                if(shopImg != null){
                    //存储图片
                    try{
                        addShopImg(shop, shopImg);
                    }catch (Exception e){
                        throw new ShopOperationException("addShopImg error " + e.getMessage());
                    }
                    i = shopDao.updateShop(shop);
                    if(i <= 0){
                        throw new ShopOperationException("更新图片失败");
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ShopOperationException("add shop " + e.getMessage());
        }

        return  new ShopExecuption(ShopSateEnum.CHECK, shop);
    }


    private void addShopImg(Shop shop, CommonsMultipartFile shopImg) {
        //获取图片的目录的相对值路径
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        String shopImgAddr = ImageUtil.generateTumbnail(shopImg, dest);
        shop.setShopImg(shopImgAddr);

    }

    @Override
    public int updateShop(Shop shop) {
        return shopDao.updateShop(shop);
    }
}
